package cn.iocoder.yudao.framework.common.util.idcard;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class OCR {

    private static final String SERVICE_HOST = "https://dm-51.data.aliyun.com";
    private static final String APP_CODE = "";

    @GetMapping("/getCardIDInfo")
    public ResponseModel getCardIDInfo(String imgPath) {
        ResponseModel responseModel = null;
        CardIDInfo cardIDInfo = new CardIDInfo();
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        // 最后在header中的格式(中间是英文空格)为Authorization:APPCODE ******
        headers.put("Authorization", "APPCODE " + APP_CODE);
        String pathImage = imgPath;
        String binaryToString = getImageBinaryToString(pathImage);
        // 根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        String bodys = "{\"inputs\": [{\"image\": {\"dataType\": 50,\"dataValue\": \"" + binaryToString
                + "\"},\"configure\": {\"dataType\": 50,\"dataValue\": \"{\\\"side\\\":\\\"face\\\"}\"}}]}";
        try {
            HttpResponse response = AliyunHttpUtils.doPost(SERVICE_HOST, path, method, headers, querys, bodys);
            HttpEntity httpEntity = response.getEntity();
            String str = EntityUtils.toString(httpEntity);
            JSONObject resultObj = new JSONObject(str);
            JSONArray outputArray = resultObj.getJSONArray("outputs");
            // 取出结果json字符串
            String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
            JSONObject out = new JSONObject(output);
            if (out.getBoolean("success")) {
                // 获取地址
                String addr = out.getString("address");
                // 获取名字
                String name = out.getString("name");
                // 获取生日
                String birth = out.getString("birth");
                // 获取性别
                String sex = out.getString("sex");
                // 获取民族
                String nationality = out.getString("nationality");
                // 获取身份证号
                String num = out.getString("num");
                cardIDInfo.setAddress(addr);
                cardIDInfo.setBirth(birth);
                cardIDInfo.setName(name);
                cardIDInfo.setNationality(nationality);
                cardIDInfo.setNum(num);
                cardIDInfo.setSex(sex);
                responseModel = new ResponseModel(cardIDInfo, true, "成功", 200);
            } else {
                responseModel = new ResponseModel(cardIDInfo, false, "predict error", 500);
            }
        } catch (Exception e) {
            responseModel = new ResponseModel(cardIDInfo, false, e.getMessage(), 500);
        }
        return responseModel;
    }

    /**
     * 获取图片的base64编码数据
     * </p>
     *
     * @param imagePath
     * @return
     */
    public static String getImageBinaryToString(String imagePath) {
        try {
            File file = new File(imagePath);
            byte[] content = new byte[(int) file.length()];
            FileInputStream finputstream = new FileInputStream(file);
            finputstream.read(content);
            finputstream.close();
            return new String(Base64.encodeBase64(content));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}